﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace antuAutoUPTools.Entries
{
    /// <summary>
    /// 日志上传类
    /// </summary>
    public class UpLog
    {
        private static string logFileName;
        private static string logFolder;
        /// <summary>
        /// 保存文件的文件名
        /// </summary>
        public static string LogFileName
        {
            get { return logFileName; }
            set { logFileName = value; }
        }
        /// <summary>
        /// 日志文件子文件夹
        /// </summary>
        public static string LogFolder
        {
            get { return logFolder; }
            set { logFolder = value; }
        }
        /// <summary>
        /// 日志文件保存
        /// </summary>
        /// <param name="RootPath">根目录</param>
        /// <param name="Content">日志内容</param>
        /// <returns></returns>
        public static bool Log_Save(string RootPath,string Content)
        {
            bool result = true;
            //生成文件路径
            SetLogSubFolder();
            string realpath = RootPath  + LogFolder;
            FileInfo fileInfo = new FileInfo(realpath);
            if (!fileInfo.Exists)
            {
                Directory.CreateDirectory(fileInfo.FullName);
            }
                try
                {
                    string txt = string.Format("{0}: {1}\r\n", DateTime.Now.ToString(), Content);
                    File.AppendAllText(fileInfo.FullName + "\\" + LogFileName,txt);
                }
                catch (Exception ex)
                {
                    string error = string.Format("文件写入失败:{0}, 文件路径:{1}", ex.ToString(), fileInfo.FullName);
                    ExceptionLog.WriteExceptionLog(ex);
                    throw new Exception(error);
                }
            return result;
        }
        #region 私有方法
        /// <summary>
        /// 根据当前日期生成子文件夹名
        /// </summary>
        private static void SetLogSubFolder()
        {
            string subPath = string.Empty;
            DateTime now = DateTime.Now;
            LogFolder = "Logs_"+now.ToString("yyyy-MM").Replace("-","_");
            LogFileName = string.Format("Log_{0}.log", now.ToString("yyyy-MM-dd").Replace("-", "_"));
        }
        #endregion
    }
}
